#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include "packet.h"

// create a single packet
int createPacket(packet* new_pck , FILE* fd, int seq_num)
{
   //struct packet new_pck;

   //char body[MTU - HEADER_SIZE];
   //size_t result;
   int result = 0;
   memset(new_pck->payload,0,PACKET_SIZE);
   result = fread(new_pck->payload, sizeof(char), PACKET_SIZE, fd);
   /*
      fseek (fd, 0, SEEK_END);
      int file_size = ftell(fd);
      rewind(fd);

      if (file_size > PACKET_SIZE)
      {
      printf("Packet size %d\n", PACKET_SIZE);
      result = fread(new_pck->payload, 1, PACKET_SIZE, fd);
      }
      else
      {
      printf("END packet size %d\n", file_size);
      result = fread(new_pck->payload, 1, file_size, fd);
      }
      */
   //memcpy(packet + HEADER_SIZE,body,MTU - HEADER_SIZE);
   //printf("Packet payload %s \n", new_pck->payload);
   fill_header(new_pck,seq_num,0,0);

   return result;
}

// fill the header of the packet
int fill_header(packet* new_pck,int seq_num, int ack_num, int check_sum)
{
   new_pck->seqnum = seq_num;
   new_pck->acknum = ack_num;
   check_sum = calculateChecksum(new_pck);
   new_pck->checksum = check_sum;

   return 0;
}

// calculate checksum of the packet
// use the algorithm in the book
// checksum = ACK + SEQ + each byte of payload
int calculateChecksum(packet* pck)
{
   int checksum;
   int i;

   checksum = pck->acknum + pck->seqnum;

   for(i = 0; i < PACKET_SIZE; i++)
   {
      checksum += pck->payload[i];
   }

   return checksum;
}
